<?php

namespace App\Console\Commands;

use App\Models\goods\Order;
use App\Models\goods\OrderGroup;
use App\Models\log\ErrorLog;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class AutoGroupCancel extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'auto:group_cancel';

    /**
     * 建议每5分钟执行一次
     *
     * 24小时未成功拼团系统自动取消
     *
     * The console command description.
     *
     * @var string
     */
    protected $description = 'order auto confirm command';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        /* 永不超时 */
        ini_set('max_execution_time', 0);
        $map['status'] = 0;
        $map[] = ['order_group_id','!=',0];
        $map[] = ['created_at','<',Carbon::now()->subDay()];
        $groups = Order::where($map)->get();

        foreach ($groups as $group){
            if ($group instanceof OrderGroup);

            DB::beginTransaction();
            try {
                $group->status = -1;
                $group->save();

                $o_map['order_group_id'] = 'order_group_id';
                $o_map['status'] = 0;
                //不需要退款的直接取消
                Order::where($o_map)->update(['status' => -1]);

                $o_map['status'] = 1;
                //需要退款的遍历处理
                $orders = Order::where($o_map)->get();
                foreach ($orders as $order){
                    if ($order instanceof Order);
                    $order->status = -1;
                    $order->save();
                    User::whereId($order->user_id)->increment('money',$order->total_price);
                }

                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                dump("AutoGroupCancel err:".$e->getMessage());
                $log['msg']     = $e->getMessage();
                $log['params']  = '';
                $log['content'] = $e;
                ErrorLog::create($log);
            }

        }

    }


}
